package com.iflyteck.MyLocal;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

@Configuration
public class MyLocalResovle implements LocaleResolver {
    // 自定义 区域解析方式
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        // 获取页面传递的语言参数  zh_CN  zh_US
        String l = request.getParameter("l");
        Locale locale = null;
        if (!StringUtils.isEmpty(l)) {
            // 如果参数不为空，就根据参数值进行手动语言切换
            String[] s = l.split("_");
            locale = new Locale(s[0], s[1]);
        } else {
            String header = request.getHeader("Accept-language");
            String[] split = header.split(",");
            String[] strArr = split[0].split("-");
            locale = new Locale(strArr[0],strArr[1]);
        }
        return locale;
    }

    @Bean  // 将自定义的MyLocaleResovle重新注册成一个类型为LocaleResovle的bean组件
    public LocaleResolver localeResolver() {
        return new MyLocalResovle();
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}
